home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyo (Python 2.5)
-
- from __future__ import with_statement
- from functional import ObjectList
- from refs import stupidref, better_ref
- from collections import defaultdict
- from error_handling import traceguard
- from operator import attrgetter
- import functools
- import logging
- import operator
- import pprint
- import sys
- import traceback
-
- try:
- sentinel
- except NameError:
- sentinel = object()
-
- log = logging.getLogger('util.primitives.funcs')
-
- def get(obj, key, default = sentinel):
-
- try:
- return obj[key]
- except (IndexError, KeyError):
- if default is sentinel:
- raise
- else:
- return default
- except TypeError:
-
- try:
- return getattr(obj, key)
- except AttributeError:
- if default is sentinel:
- raise
- else:
- return default
- except:
- default is sentinel
-
-
- None<EXCEPTION MATCH>AttributeError
-
-
-
- def ischeck(f):
-
- def checker(v):
-
- try:
- r = f(v)
- except:
- return False
-
- if type(r) is bool:
- return r
- else:
- return True
-
- return checker
-
-
- def itercheck(x, exclude = (basestring,)):
-
- try:
- iter(x)
- except:
- return False
-
- if not isinstance(x, exclude):
- return True
- else:
- return False
-
- isint = ischeck(int)
- isiterable = ischeck(itercheck)
- isnumber = ischeck(float)
-
- def make_first(seq, item):
-
- try:
- idx = seq.index(item)
- seq.pop(idx)
- except ValueError:
- pass
-
- seq.insert(0, item)
-
-
- def do(seq_or_func, seq = None):
- if seq is None:
- for x in seq_or_func:
- pass
-
- else:
- for x in seq:
- seq_or_func(x)
-
-
-
- def find(seq, item):
-
- try:
- return seq.index(item)
- except ValueError:
- return -1
-
-
-
- def groupby(seq, key = (lambda x: x)):
- res = defaultdict(list)
- for item in seq:
- res[key(item)].append(item)
-
- for k in res:
- yield (k, res[k])
-
-
-
- class Delegate(ObjectList):
- VETO = object()
-
- def __init__(self, iterable = [], ignore_exceptions = None, collect_values = False):
- list.__init__(self, iterable)
- self.__dict__['collect_values'] = collect_values
- None(object.__setattr__, self, 'ignore_exceptions' if ignore_exceptions is not None else tuple())
-
-
- def __iadd__(self, f):
- if isinstance(f, list):
- for thing in f:
- self.__iadd__(thing)
-
- else:
- self.append(f)
- return self
-
-
- def __isub__(self, f):
- if not isiterable(f):
- f = (f,)
-
- for x in f:
- self.remove(x)
-
- return self
-
-
- def __ipow__(self, d):
- self(**d)
- return self
-
-
- def __imul__(self, a):
- self(*a)
- return self
-
-
- def __idiv__(self, tup):
- (a, k) = tup
- self(*a, **k)
- return self
-
-
- def __call__(self, *a, **k):
- result = [
- None]
- for call in self:
-
- try:
- result.append(call(*a, **k))
- except self.ignore_exceptions:
- self.remove(call)
- except Exception:
- traceback.print_exc()
-
- if result[-1] is self.VETO:
- break
-
- if not self.collect_values:
- result = result[-1:]
- continue
-
- if self.collect_values:
- result.pop(0)
- else:
- result = result[-1]
- return result
-
-
- def call_and_clear(self):
- result = self()
- self[:] = []
- return result
-
-
- def __repr__(self):
- funcinfo = funcinfo
- import util
- return '<%s: [%s]>' % (type(self).__name__, (', '.join,)((lambda .0: for f in .0:
- funcinfo(f))(self)))
-
-
- def add_unique(self, cb):
- if cb not in self:
- self.append(cb)
-
-
-
- def remove_maybe(self, cb):
- if cb in self:
- self.remove(cb)
-
-
-
- objset = object.__setattr__
-
- class PausableDelegate(Delegate):
-
- def __init__(self):
- Delegate.__init__(self)
- objset(self, 'paused', False)
-
-
- def __call__(self, *a, **k):
- if self.paused:
- (None, None, self.paused_calls.append)((lambda : Delegate.__call__(self, *a, **k)))
- return None
- else:
- return Delegate.__call__(self, *a, **k)
-
-
- def pause(self):
- if not self.paused:
- objset(self, 'paused', True)
- objset(self, 'paused_calls', [])
- return True
-
- return False
-
-
- def unpause(self):
- if self.paused:
- objset(self, 'paused', False)
- if self.paused_calls:
- for call in self.paused_calls:
- traceguard.__enter__()
-
- try:
- call()
- finally:
- pass
-
-
- del self.paused_calls[:]
-
- return True
-
- return False
-
-
-
- class WeakDelegate(object):
-
- def __init__(self):
- self.cbs = []
-
-
- def append(self, cb, obj = None):
- self.cbs.append(better_ref(cb, obj = obj))
-
-
- def __iadd__(self, cb):
- self.cbs.append(better_ref(cb))
- return self
-
-
- def __isub__(self, cb):
- new_cbs = []
- for cbref in self.cbs:
- callback = cbref()
- if cb is not callback:
- new_cbs.append(cb)
- continue
-
- self.cbs = new_cbs
- return self
-
-
- def __call__(self, *a, **k):
- new_cbs = []
- cbs = self.cbs[:]
- self.cbs[:] = []
- for cbref in cbs:
- callback = cbref()
- if callback is not None:
- new_cbs.append(cbref)
-
- try:
- callback(*a, **k)
- except Exception:
- traceback.print_exc()
- except:
- None<EXCEPTION MATCH>Exception
-
-
- None<EXCEPTION MATCH>Exception
-
- self.cbs[:] = new_cbs
-
-
-
- def autoassign(self, locals):
- for key, value in locals.iteritems():
- if key == 'self':
- continue
-
- setattr(self, key, value)
-
-
-
- def flatten(seq):
- lst = []
- for el in seq:
- if isinstance(el, (list, tuple)):
- lst.extend(flatten(el))
- continue
- lst.append(el)
-
- return lst
-
-
- def dictargs(**argmap):
-
- def decorator(func):
-
- def newf(self, response):
-
- try:
- args = _[1]
- except KeyError:
- print >>sys.stderr, 'Error matching argument for', func.__name__
- raise
-
- return func(self, *args)
-
- newf = (None, functools.wraps(func))(newf)
- return newf
-
- return decorator
-
-
- def dictargcall(func, argdict, argmapping):
- argdict = argdict.copy()
- args = []
- kwargs = { }
- code = func.func_code
- argcount = code.co_argcount
- argnames = code.co_varnames[:argcount]
- if not func.func_defaults:
- pass
- defaults = ()
- _takes_args = bool(code.co_flags & 4)
- takes_kwargs = bool(code.co_flags & 8)
- if argnames and argnames[0] == 'self':
- argnames = argnames[1:]
- argcount -= 1
-
- for argname in argnames[:argcount - len(defaults)]:
- if argname not in argmapping:
- raise ValueError('required argument %s is not in mapping\ngiven mapping: %s' % (argname, pprint.pformat(argmapping)))
-
- real_name = argmapping[argname]
- if real_name not in argdict:
- raise ValueError('required argument "%s" (%s) is not in argument dictionary\ngiven arguments: %s' % (argname, real_name, pprint.pformat(argdict)))
-
- args.append(argdict[real_name])
- del argdict[real_name]
-
- default_index = 0
- for argname in argnames[argcount - len(defaults):]:
- if argname not in argmapping or argmapping[argname] not in argdict:
- args.append(defaults[default_index])
- else:
- args.append(argdict[argmapping[argname]])
- del argdict[argmapping[argname]]
- default_index += 1
-
- if takes_kwargs:
- for k, v in argdict.iteritems():
- if k in argmapping:
- kwargs[argmapping[k]] = v
- continue
- kwargs[str(k)] = v
-
-
- if not takes_kwargs:
- return func(*args)
- else:
- return func(*args, **kwargs)
-
-
- def funcToMethod(func, clas, method_name = None):
- func.im_class = clas
- func.im_func = func
- func.im_self = None
- if not method_name:
- method_name = func.__name__
-
- clas.__dict__[method_name] = func
-
-
- def attach_method(obj, func, name = None):
- if not name:
- pass
- name = func.__name__
- cls = obj.__class__
- cls.temp_foo = func
- obj.__setattr__(name, cls.temp_foo)
- del cls.temp_foo
-
-
- class InheritableProperty(object):
-
- def __init__(self, fget = None, fset = None, fdel = None, doc = None):
- self.fget = fget
- self.fset = fset
- self.fdel = fdel
- self.__doc__ = doc
-
-
- def __get__(self, obj, objtype = None):
- if obj is None:
- return self
-
- if callable(self.fget):
- return self.fget(obj)
-
- if isinstance(self.fget, basestring):
- return getattr(obj, self.fget)()
-
- raise AttributeError('unreadable attribute')
-
-
- def __set__(self, obj, value):
- if callable(self.fset):
- return self.fset(obj, value)
-
- if isinstance(self.fset, basestring):
- return getattr(obj, self.fset)(value)
-
- raise AttributeError("can't set attribute")
-
-
- def __delete__(self, obj):
- if callable(self.fdel):
- return self.fdel(obj)
-
- if isinstance(self.fdel, basestring):
- return getattr(obj, self.fdel)()
-
- raise AttributeError("can't delete attribute")
-
-
- iproperty = InheritableProperty
-
- def gen_sequence(func):
- cannotcompile = cannotcompile
- import util.introspect
-
- def wrapper(*args, **kwargs):
- gen = func(*args, **kwargs)
- val = gen.next()
-
- try:
- gen.send(stupidref(gen))
- except StopIteration:
- pass
-
- return val
-
- wrapper = cannotcompile((functools.wraps(func),)(wrapper))
- return wrapper
-
-
- def removedupes(seq, key = (lambda x: x)):
- s = set()
- uniqueseq = []
- for elem in seq:
- if key(elem) not in s:
- uniqueseq.append(elem)
- s.add(key(elem))
- continue
-
- return uniqueseq
-
-
- def lispify(*args):
-
- try:
- iter(args[0])
- except:
- pass
-
- args = args[0]
- return reduce((lambda x, y: (lambda : x(y(*a, **k)))
- ), args)
-
-
- class CallCounter(object):
-
- def __init__(self, trigger, func, *args, **kwargs):
- self._count = -1
- self._trigger = trigger
- self._func = func
- self._args = args
- self._kwargs = kwargs
- self()
-
-
- def __call__(self):
- self._count += 1
- if self._count == self._trigger:
- self._func(*self._args, **self._kwargs)
-
-
-
- def func_code(self):
- return self._func.func_code
-
- func_code = property(func_code)
-
-
- def readonly(attr):
- return property(attrgetter(attr))
-
-
- def takemany(n, iterable):
- while n > 0:
- yield iterable.next()
- n -= 1
-
-
- def boolify(s):
- return s.lower() in ('yes', 'true', '1')
-
- if __name__ == '__main__':
- import doctest
- doctest.testmod(verbose = True)
-
-